package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.util.BaseContext;
import com.itheima.reggie.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        //1 获取本次请求的URL
        //强转为HttpServletRequest 为获取session
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        //获取请求的uri
        String requestURI = httpServletRequest.getRequestURI();
        log.info("拦截的uir:{}", requestURI);
        //2 判断本次请求是否需要处理
        //定义直接放行的uri
        String[] uris = {"/employee/login", "/employee/logout", "/backend/**", "/front/**"};
        if (check(requestURI, uris)) {
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            return;
        }
        //4 判断登录状态 如果已经登录 则直接放行
        Object employeeId = httpServletRequest.getSession().getAttribute("employeeId");
        if (employeeId != null) {
            log.info("用户已经登录:{}", httpServletRequest.getSession().getAttribute("employeeId"));
            BaseContext.setCurrentId((Long)employeeId);
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }
        //5 未登录则返回登录页面
        log.info("用户未登录");
        httpServletResponse.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    private boolean check( String requestURI, String[] uris) throws IOException, ServletException {
        boolean match = false;
        for (String uir : uris) {
            match = PATH_MATCHER.match(uir, requestURI);
            //3 如果不需要处理，则直接放行
            //match为true,说明属于直接放行的uri，直接放行
            if (match) {
                return true;
            }
        }
        return false;
    }
}
